﻿using Bear.Library.Util;
using Bear.Library.WinApi;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Text;
using System.Reflection;

namespace Bear.BLL
{
    public class ScriptHelper
    {
        public static string[] GetAssemblies()
        {
            string[] astr = new string[] { 
                "system.dll",
                "system.data.dll",
                "system.xml.dll",
                "System.Core.dll",
                "System.Drawing.dll",
                "System.Windows.Forms.dll",
                "Emgu.CV.dll",
                "Emgu.Util.dll",
                Path.Combine(Environment.CurrentDirectory, "Bear.BLL.dll"),
                Path.Combine(Environment.CurrentDirectory, "Bear.Library.dll")
            };

            return astr;
        }

        public static ScriptBase Compile(string path)
        {
            //得到一个CSharp的编译器
            using (CSharpCodeProvider compiler = new CSharpCodeProvider())
            {

                //读取文件

                string content = File.ReadAllText(path, Encoding.Unicode);


                CompilerParameters compilerParameters = new CompilerParameters(ScriptHelper.GetAssemblies())
                {
                    //这是指示说我们输出的程序集是dll，而不是exe
                    GenerateExecutable = false,
                    //这是指示在内存中创建该程序集
                    GenerateInMemory = true,
                    // 不将编译警告作为错误  
                    TreatWarningsAsErrors = false
                };

                //执行编译
                CompilerResults result = compiler.CompileAssemblyFromSource(compilerParameters, content);

                if (result.Errors.HasErrors)
                {
                    throw new Exception(result.Errors[0].ErrorText);
                }

                ScriptBase script = result.CompiledAssembly.CreateInstance(result.CompiledAssembly.ExportedTypes.FirstOrDefault().FullName) as ScriptBase;

                return script;
            }
        }
    }
}
